package com.xhis.homenurse;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.preference.PreferenceManager;
import androidx.appcompat.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.tencent.smtt.sdk.QbSdk;
import com.xhis.homenurse.tools.DialogTools;

import org.w3c.dom.Document;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class GLobalApp extends Application {
    @Override
    public void onCreate()
    {
        super.onCreate();
        QbSdk.initX5Environment(this, null);
    }

    /**
     * 获取程序版本
     *
     * @param c
     * @return 版本号，否则返回空字符串
     * @throws PackageManager.NameNotFoundException
     */
    public static String getAppVersion(Context c)
    {
        try {
            PackageInfo info = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
            // 当前应用的版本名称
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取程序版本码
     */
    public static int getVersionCode(Context c)
    {
        try {
            PackageManager packageManager = c.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(c.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取sd卡目录
     */
    public static String getSDCardPath()
    {
        // 判断sd卡是否存在
        boolean sdCardExist = Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState());
        if (sdCardExist) {
            File sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
            return sdDir.toString();
        }

        return null;
    }

    /**
     * 获取xml文档
     */
    public static Document getDocument(String xml) throws Exception
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 取得DocumentBuilderFactory实例
        DocumentBuilder builder = factory.newDocumentBuilder(); // 从factory获取DocumentBuilder实例

        ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));

        Document doc = builder.parse(is); // 解析输入流 得到Document实例

        return doc;
    }

    /**
     * 获取xml字符串
     *
     * @param doc xml文档
     * @return
     * @throws TransformerException
     */
    public static String getString(Document doc) throws TransformerException
    {
        TransformerFactory transFactory = TransformerFactory.newInstance();// 取得TransformerFactory实例
        Transformer transformer = transFactory.newTransformer(); // 从transFactory获取Transformer实例
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // 设置输出采用的编码方式
        transformer.setOutputProperty(OutputKeys.INDENT, "no"); // 是否自动添加额外的空白
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // 是否忽略XML声明

        StringWriter writer = new StringWriter();

        Source source = new DOMSource(doc); // 表明文档来源是doc
        Result result = new StreamResult(writer);// 表明 目标结果为writer
        transformer.transform(source, result); // 开始转换

        return writer.toString();
    }

    /**
     * 显示提示对话框(系统默认的)
     */
    public static void showMessageDialog(Context context, String text)
    {
        if(context instanceof Activity){
            if(((Activity) context).isFinishing()){
                return;
            }
        }
        new AlertDialog.Builder(context).setIcon(R.mipmap.logo)
                .setCustomTitle(DialogTools.getDialgoTitleView(context, "提示",R.mipmap.hintdialog))
                .setMessage(text)
                .setPositiveButton(R.string.confirm, null).show();
    }

    // 隐藏输入面板
    public static void hideInputPanel(Context activity, View editView)
    {
        InputMethodManager imm = (InputMethodManager) activity
                .getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editView.getWindowToken(), 0);
    }

    /**
     * 获取UUID
     */
    public static String getSerialNumber(Context c)
    {
        // TelephonyManager telephonyManager=(TelephonyManager)
        // c.getSystemService(Context.TELEPHONY_SERVICE);
        // String imei = telephonyManager.getDeviceId();
        // String serialNumber = getUniquePsuedoID();
        // Log.i("basket",getUniquePsuedoID()+"....");
        String serialNumber = "";
        SharedPreferences spf = PreferenceManager
                .getDefaultSharedPreferences(c);
        if (spf.getString("UUID", "").equals("")) {
            serialNumber = UUID.randomUUID().toString();
            spf.edit().putString("UUID", serialNumber).commit();
        } else
            serialNumber = spf.getString("UUID", "");
        Log.i("basket", serialNumber + "....");
        return serialNumber;
    }

    public ArrayList<Activity> list = new ArrayList<Activity>();

    /**
     * Activity关闭时，删除Activity列表中的Activity对象
     */
    public void removeActivity(Activity a)
    {
        list.remove(a);
    }

    /**
     * 向Activity列表中添加Activity对象
     */
    public void addActivity(Activity a)
    {
        list.add(a);
    }

    /**
     * 关闭Activity列表中的所有Activity
     */
    public void finishActivity()
    {
        for (Activity activity : list)
        {
            if (null != activity)
            {
                activity.finish();
            }
        }
        // 杀死该应用进程
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    public static String getAppProcessName(Context context) {
        //当前应用pid
        int pid = android.os.Process.myPid();
        //任务管理类
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //遍历所有应用
        List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            if (info.pid == pid)//得到当前应用
                return info.processName;//返回包名
        }
        return "";
    }

    /**
     * 获取程序签名
     */
    public static String getSign(Context context) {
        PackageManager pm = context.getPackageManager();
        List<PackageInfo> apps = pm.getInstalledPackages(PackageManager.GET_SIGNATURES);
        Iterator<PackageInfo> iter = apps.iterator();
        while (iter.hasNext()) {
            PackageInfo packageinfo = iter.next();
            String packageName = packageinfo.packageName;
            if (packageName.equals(getAppProcessName(context))) {
                String sign = packageinfo.signatures[0].toCharsString();
                Log.e("sign", sign);
                return sign;
            }
        }
        return null;
    }
}
